home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 14038 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: mudskipper.cac.psu.edu!user
  2. From: fcusack@tdx.org (frank.)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Union type
  5. Date: Thu, 11 Apr 1996 09:25:00 -0400
  6. Organization: Soylent Green is People!!
  7. Message-ID: <fcusack-1104960925000001@mudskipper.cac.psu.edu>
  8. References: <4kh43f$h4f@dewey.csun.edu>
  9. NNTP-Posting-Host: mudskipper.cac.psu.edu
  10.  
  11. In article <4kh43f$h4f@dewey.csun.edu>, kc44097@csun.edu (chen) wrote:
  12.  
  13. >      I have a question about union,can anyonegive me some advice?
  14. > Please e-mail me
  15. >                         kc44097@huey.csun.edu
  16. >                  Thankx
  17. > -------------------------------------------------------------
  18. > #include <stdio.h>
  19. > union {
  20. >   int   integer;
  21. >   float floating;
  22. > } myUnion;
  23. > main()
  24. > {
  25. >   myUnion.integer = 1;
  26. >    printf("The value of integer is %d\n",     myUnion.integer);
  27. >    printf("The value of floating is %f\n\n",  myUnion.floating);
  28. >    printf("The value of \"cast\" is %f\n",    (float) myUnion.integer);
  29. >    printf("The value of \"magic\" is %f\n\n", myUnion.integer);
  30. >    printf("The meaning of life ``%d''\n",     (int) myUnion.floating);
  31. >    return (0);
  32. > }
  33. >    The optput is :
  34. >       The value of integer is 1
  35. >       The value of floating is 0.000000
  36. >       The value of cast is 1.000000
  37. >       The value of magic is 0.000000
  38. >       The meaning of life ``0''
  39. >     My question is : Why myUnion.integer is 1 but myUnion.floating is
  40. >     0.000000;Why myUnion.integer change to 0.000000 in 4th printf(),
  41. >     and why myUnion.floating is 0 in 5th printf()?
  42.  
  43. When retreiving the value of a union, you must retrieve the same type as
  44. most recently assigned. Other behavior is undefined. IOW, don't do it!!
  45.  
  46. ie, in your example, since you assigned a value to the integer value of
  47. your union, you can ONLY retrieve the integer value.
  48.  
  49. ~Frank
  50.  - Through the modem, past the router, over the firewall.. nothing but Net -
  51.  -  PGP ID: 1C0F6685 | NCB#56 | Visit me --> http://www.tdx.org/~fcusack/  -
  52.